<?php
require_once 'conf.php';
require_once "classes.php";
require_once "services/securityServices.php";
require_once "services/budgetServices.php";
require_once "services/BusinessLogic.php";
require_once "errorCodes.php";
require_once "dto/Action.php";
require_once "dto/Action.php";
require_once 'httpFilter.php';

$errMessage = "";
$errCode = 0;
try {

	$actionName = $_REQUEST["action"];
	$action = new Action($actionName);

	error_log("SERVICE REQUESTED ::::: ".$action->serviceClass);

	$class = new ReflectionClass($action->serviceClass);
	$classInstance = $class->newInstance();

	$params = $action->parameters;

	$parameters = array();

	foreach ($params as $param){
		$required = $param->required;

		if (($required == "true") && (isset($_REQUEST[$param->name]))){
			$parameters[$param->name] = $_REQUEST[$param->name];
		} else if (($required == "false") && (isset($_REQUEST[$param->name]))){
			$parameters[$param->name] = $_REQUEST[$param->name];
		} else if (($required == "false") && (!isset($_REQUEST[$param->name]))){
			$parameters[$param->name] = "";
		}

		if($param->name != "password")
		{
			error_log("PARAM: ".$param->name." VALUE: ".$parameters[$param->name]);
		}
		
		//$parameters[$param] = $_REQUEST[$param];
		/*if ($_REQUEST[$param] == ""){
			throw new Exception('011');
			}*/
	}

	if($actionName != "createUser"){
		//We need to send the userId for every call except for createUser.
		$parameters["userid"] = $_SESSION["userid"];
		error_log("userId: ". $parameters["userid"]);
	}
	echo $classInstance->$actionName($parameters);

	if (isset($_SESSION['mobile'])){
		session_destroy();
	}

} catch (Exception $e) {
	error_log("Error!: " . $e->getMessage());

	$errCode = $e->getMessage();
	$errorCodes = new ErrorCodes;
	$errMessage = $errorCodes->getErrorMessage($e->getMessage());

	error_log("Error Message: " . $errMessage);

	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "<errMessage>";
	echo $errMessage;
	echo "</errMessage>";
	echo "</result>";
}

function setCustomError(){
	set_error_handler("customError");
}


function customError($errno, $errstr, $file, $line){
	if (!(error_reporting() & $errno)) {
		// This error code is not included in error_reporting
		error_log($errstr);
		return;
	}

	switch ($errno) {
		case E_USER_ERROR:
			error_log("Fatal error on line $errline in file $errfile $errstr");
			break;

		case E_USER_WARNING:
			error_log("Warning on line $errline in file $errfile $errstr");
			break;

		case E_USER_NOTICE:
			error_log("Notice on line $errline in file $errfile $errstr");
			break;

		default:
			error_log("Default error!!!");
			break;
	}

	/* Don't execute PHP internal error handler */
	return true;
}

?>